package com.hnchances.wjb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hnchances.wjb.Dto.UserDto;
import com.hnchances.wjb.Service.Impl.MsmServiceImpl;
import com.hnchances.wjb.Service.StudentService;
import com.hnchances.wjb.Service.TeacherService;
import com.hnchances.wjb.Service.UserService;
import com.hnchances.wjb.common.R;
import com.hnchances.wjb.entity.Message;
import com.hnchances.wjb.entity.Student;
import com.hnchances.wjb.entity.Teacher;
import com.hnchances.wjb.entity.User;
import com.hnchances.wjb.jwt.JwtResultMap;
import com.hnchances.wjb.jwt.JwtUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    StudentService studentService;
    @Autowired
    UserService userService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    private JwtResultMap resultMap;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MsmServiceImpl msmService;

    //用户注册
    @Transactional
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R<String> register(@RequestBody UserDto userDto) throws IOException {

//        以通过phone手机号为key从Redis获取验证码：有空和不为空两种情况
        String code = (String) redisTemplate.opsForValue().get(userDto.getPhone());

        //验证码和短信是否相等
        if (code.equals(userDto.getCode())) {
            return userService.register(userDto);

        }
        return R.error("验证码错误", 400);
    }


    //用户修改
    @ApiOperation("用户修改")
    @RequiresRoles(logical = Logical.OR, value = {"student", "teacher"})
    @RequiresPermissions("roles:user:update")
    @PostMapping("/update")
    public R<String> update(@RequestBody User user){

        user.setUpdateDateTime(LocalDateTime.now());

          userService.updateById(user);
        return R.success("用户信息修改成功");
    }

    //老师删除用户表
    @ApiOperation("老师删除用户表中的学生")
    @RequiresRoles( value = "teacher")
    @RequiresPermissions("roles:user:del")
    @PostMapping("/del")
    public R<String> del(@RequestBody User user,Integer SClassId){
        Integer id = user.getId();
        Integer classId = user.getClassID();
        //软删除 将用户状态改为1
        user.setStatus(1);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId,id)
                .eq(User::getClassID,SClassId)
                .eq(User::getUserName, user.getUserName());
        userService.update(lambdaQueryWrapper);
        return R.success("用户信删除成功");
    }



    //用户查询
    @ApiOperation("用户查询自己的信息")
    @RequiresRoles(logical = Logical.OR, value = {"student", "teacher"})
    @RequiresPermissions("roles:user:userinfo")
    @PostMapping("/userinfo")
    public R<User> userinfo(@RequestBody User user, HttpServletRequest request){
     String username = JwtUtil.getUsernameFromToken("token");
     //根据token 传来的username 查询用户的信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,username);
     User user1 = userService.getOne(lambdaQueryWrapper);
     //密码设置为不可见
     user.setPassWord("****");
     return R.success(user);
    }

    //用户登录
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public JwtResultMap login(@RequestBody String username, @RequestBody String password) {
        LambdaQueryWrapper<User> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getTrueName,username);
        User user = userService.getOne(lambdaQueryWrapper);
user.setLastLoginDateTime(LocalDateTime.now());
userService.update(user,lambdaQueryWrapper);
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (null == user) {
            return resultMap.fail().code(401).message("账号错误");
        } else if (!password.equals(user.getPassWord())) {
            return resultMap.fail().code(401).message("密码错误");
        }
        return resultMap.success().code(200).message(JwtUtil.createToken(username));
    }


    //当authorized权限不足时访问的接口
    @ApiOperation("当authorized权限不足时访问的接口")
    @ResponseBody
    @PostMapping("/unauthorized/{message}")
    public JwtResultMap unauthorized(@PathVariable String message) {
        return resultMap.success().code(401).message(message);
    }
}
